package com.niit.service.impl;

import com.niit.entity.Company;
import com.niit.repository.CompanyRepository;
import com.niit.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyRepository companyRepository;

    @Override
    public Page<Company> getCompanyPage(Integer page, Integer size, String companyName) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Company> companyPage;

        if (companyName != null && !companyName.isEmpty()) {
            companyPage = companyRepository.findByCompanyNameContaining(companyName, pageable);
        } else {
            companyPage = companyRepository.findAll(pageable);
        }

        return companyPage;
    }

    @Override
    @Transactional
    public void deleteCompany(Integer id) {
        companyRepository.deleteById(id);
    }

    @Override
    public Company addCompany(Company company) {
        return companyRepository.save(company);
    }

    @Override
    public List<Company> getAllCompany() {
        return companyRepository.findAll();
    }

    @Override
    public Company getCompanyById(Integer id) {
        return companyRepository.findById(id).orElse(null);
    }
}